//
//  RegisterViewController.m
//  Article
//
//  Created by Haricot_cpc17 on 16/4/25.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "RegisterViewController.h"
#import "LCTabBarController.h"
//#import "RetrievePasswordViewController.h"
#import "AFNetworking.h"
//#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "EditorViewController.h"
#import "LoginViewController.h"


@interface RegisterViewController ()

@property (nonatomic,strong)UITextField *phoneTextField;//手机号
@property (nonatomic,strong)UITextField *passwordTextField;//密码
@property (nonatomic,strong)UITextField *ReTextfiled;//验证码
@property (nonatomic,strong)UITextField *inviteTextField;//邀请码



@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createUI];
    self.view.backgroundColor = [UIColor whiteColor];
}

-(void)createUI{
    
    _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *106/667 + HEIGHT *0/667, WIDTH - WIDTH *40/375, HEIGHT *40/667)];
    _phoneTextField.secureTextEntry = YES;
    _phoneTextField.placeholder = @"请输入手机号";
    [_phoneTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_phoneTextField setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [_phoneTextField setBorderStyle:UITextBorderStyleNone];
    [self.view addSubview:_phoneTextField];
    _phoneTextField.borderStyle = UITextBorderStyleRoundedRect;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTextField.secureTextEntry = NO;
    _phoneTextField.tag = 100;
    
    _passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *106/667 + HEIGHT *60/667, WIDTH - WIDTH *40/375, HEIGHT *40/667)];
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.placeholder = @"请输入密码";
    [_passwordTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordTextField setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [_passwordTextField setBorderStyle:UITextBorderStyleNone];
    [self.view addSubview:_passwordTextField];
    _passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.tag = 101;
    
    
    //验证码
    _ReTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *106/667 + HEIGHT *120/667, WIDTH - WIDTH *260/375, HEIGHT *40/667)];
    _ReTextfiled.secureTextEntry = YES;
    _ReTextfiled.placeholder = @"请输入验证码";
    [_ReTextfiled setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_ReTextfiled];
    [_ReTextfiled setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_ReTextfiled setBorderStyle:UITextBorderStyleNone];
    _ReTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    _ReTextfiled.secureTextEntry = NO;
    _ReTextfiled.tag = 103;
    

    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH * 160/375, HEIGHT *106/667 + HEIGHT *120/667, WIDTH - WIDTH *180/375, HEIGHT *40/667)];
    button.backgroundColor = UIColorFromRGB(MYColor);
    button.layer.cornerRadius = 5;
    button.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    [button setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.view addSubview:button];
    
    _inviteTextField = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *156/667 + HEIGHT *120/667, WIDTH - WIDTH *40/375, HEIGHT *40/667)];
    _inviteTextField.secureTextEntry = YES;
    _inviteTextField.placeholder = @"请输入邀请码";
    [_inviteTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_inviteTextField setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [_inviteTextField setBorderStyle:UITextBorderStyleNone];
    [self.view addSubview:_inviteTextField];
    _inviteTextField.borderStyle = UITextBorderStyleRoundedRect;
    _inviteTextField.secureTextEntry = NO;
    _inviteTextField.tag = 102;
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textFieldClick)];
    [self.view addGestureRecognizer:tap];
    
    
   // [self.view addSubview:_textField];
    //提交按钮
    UIButton *submitBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH *40/375, HEIGHT *342/667, WIDTH - WIDTH *80/375,40)];
    submitBtn.backgroundColor = UIColorFromRGB(MYColor);
    [submitBtn setTitle:@"注册" forState:UIControlStateNormal];
    submitBtn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    [self.view addSubview:submitBtn];
    [submitBtn addTarget:self action:@selector(registClick:) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.layer.cornerRadius = 5;
    
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH *40/375, HEIGHT *390/667, WIDTH - WIDTH *80/375, 40)];
    backBtn.backgroundColor = UIColorFromRGB(MYColor);
    [backBtn setTitle:@"返回登录" forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    [self.view addSubview:backBtn];
    backBtn.layer.cornerRadius = 5;
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)textFieldClick{
    UITextField *textField = [(UITextField *)self.view viewWithTag:100];
    [textField resignFirstResponder];
    
    UITextField *textField1 = [(UITextField *)self.view viewWithTag:101];
    [textField1 resignFirstResponder];
    
    UITextField *textFiele2 = [(UITextField *)self.view viewWithTag:102];
    [textFiele2 resignFirstResponder];
    
    UITextField *textField3 = [(UITextField *)self.view viewWithTag:103];
    [textField3 resignFirstResponder];
}


-(void)registClick:(UIButton *)button{
    NSLog(@"注册");
    
//    UITextField *nametextFied = (id)[self.view viewWithTag:10];
//    UITextField *codetextFied = (id)[self.view viewWithTag:11];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    if ([_phoneTextField.text isEqualToString:@""]) {
        alert.title = @"手机号不能为空!";
        alert.tag = 1;
        [alert show];
    }if ([_passwordTextField.text isEqualToString:@""] ) {
            alert.title = @"密码不能为空!";
            alert.tag = 2;
            [alert show];
    }if([_ReTextfiled.text isEqualToString:@""]){
            alert.title = @"验证码不能为空!";
            alert.tag = 3;
    }else{
        
            NSDictionary *dic = @{@"mobile":_phoneTextField.text,
                                  @"password":_passwordTextField.text,
                                  @"reg_verify":@"123456",
                                  @"invite_code":@"1423",
                                  @"img_verify":@"2fy63"};
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            [manager POST:@"http://hmyx.ijiaque.com/app/user/register.html" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
                if ([str isEqualToString:@"1"]) {
                    
                    NSDictionary *dic2 = [dic1 objectForKey:@"data"];
                    NSDictionary *levelDic = [dic2 objectForKey:@"level"];
                    NSLog(@"levelDic  %@",levelDic);
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

                    [user synchronize];
                    NSLog(@"user %@",user);
                    NSLog(@"user_token %@",[user objectForKey:@"user_token"]);
                    
                    [self.view makeToast:@"注册成功" duration:0.5 position:CSToastPositionCenter];
                    NSLog(@"%@",dic1[@"info"]);
                    [self login];

                    
                }else{
                    
                    [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
                    NSLog(@"%@",dic1[@"info"]);
                }
            }
                  failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                      //   [MBProgressHUD hideHUDForView:self.view animated:YES];
                      [self.view makeToast:@"注册失败!" duration:1.0 position:CSToastPositionCenter];
                      NSLog(@"%@",error.description);
                      
                  }];
        }
    

}
-(void)login{
    NSString * username = _phoneTextField.text;
    NSString * password = _passwordTextField.text;
    NSDictionary *dic = @{@"mobile":_phoneTextField.text,
                          @"password":_passwordTextField.text};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:@"http://hmyx.ijiaque.com/app/user/login.html" parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
        if ([str isEqualToString:@"1"]) {
            NSDictionary *dic2 = [dic1 objectForKey:@"data"];
            NSDictionary *levelDic = [dic2 objectForKey:@"level"];
            NSLog(@"levelDic  %@",levelDic);
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            //登录成功后把用户名和密码存储到UserDefault
            [user setObject:username forKey:@"mobile"];
            [user setObject:password forKey:@"password"];
            [user setObject:[dic2 objectForKey:@"uid"] forKey:@"uid"];
            [user setObject:[dic2 objectForKey:@"nickname"] forKey:@"nickname"];
            [user setObject:[dic2 objectForKey:@"avatar256"] forKey:@"imageurl"];
            [user setObject:[dic2 objectForKey:@"user_token"] forKey:@"token"];
            [user setObject:[dic2 objectForKey:@"sex"] forKey:@"sex"];
            
            [user synchronize];
            LCTabBarController *LCTabVC = [[LCTabBarController alloc]init];
            [self presentViewController:LCTabVC animated:YES completion:nil];
            NSLog(@"内部登录成功");
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"内部登录失败");
    }];
    
}

-(void)backClick:(UIButton *)button{
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
